package com.csx.framework.springboot.sample.data.transaction.service;

import com.csx.framework.springboot.sample.data.transaction.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * <p> what does this class do ? </p>
 * <p> How does it work ?</p>
 * <p> Why does it do this ?</p>
 *
 * @author cuisongxu
 * @date 2024/12/21 周六 13:27
 */
@Component
public class UserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public int insertUser(Long id, String firstName, String lastName, Integer age, String city) {
        String sql = "INSERT INTO user (id, first_name, last_name, age, city) VALUES (?, ?, ?, ?, ?)";
        return jdbcTemplate.update(sql, id, firstName, lastName, age, city);
    }

    public int insertUserFail(Long id, String firstName, String lastName, Integer age, String city) {
        throw new RuntimeException("插入失败");
    }

    // 查询所有用户
    public List<User> getAllUsers() {
        String sql = "SELECT * FROM user";
        return jdbcTemplate.query(sql, (rs, rowNum) -> new User(
                rs.getLong("id"),
                rs.getString("first_name"),
                rs.getString("last_name"),
                rs.getInt("age"),
                rs.getString("city")
        ));
    }

}
